package com.example.bingobox.ui.state;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bingobox.R;
import com.example.bingobox.databinding.ItemStateBinding;
import com.example.bingobox.dialog.CityManageDialog;
import com.example.bingobox.dialog.LocationManageDialog;
import com.example.bingobox.dialog.LocationMarkDialog;
import com.example.bingobox.dialog.LocationTypeDialog;
import com.example.bingobox.dialog.LocationTypeManageDialog;
import com.example.bingobox.model.State;
import com.example.bingobox.utils.LocationUtils;
import com.example.bingobox.view.HealthSelector;
import com.example.bingobox.view.MoodSelector;
import com.example.bingobox.view.NetworkSelector;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class StateAdapter extends RecyclerView.Adapter<StateAdapter.ViewHolder> {
    private static final int LOCATION_PERMISSION_REQUEST = 1001;
    private final Context context;
    private final State state;
    private final Gson gson;

    public StateAdapter(Context context, State state) {
        this.context = context;
        this.state = state;
        this.gson = new GsonBuilder().setPrettyPrinting().create();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_state, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        updateCityInfo(holder);
        updateLocationInfo(holder);
        setupListeners(holder);
        
        // 设置心情和健康状态
        holder.moodSelector.setMood(state.getMood());
        holder.healthSelector.setHealth(state.getHealth());
    }

    private void updateCityInfo(ViewHolder holder) {
        State.Location currentCity = state.getCurrentCity();
        if (currentCity != null) {
            holder.currentCity.setText(currentCity.getName());
            holder.cityType.setText(state.getCurrentCityType());
        } else {
            holder.currentCity.setText("未知");
            holder.cityType.setText("");
        }
    }

    private void updateLocationInfo(ViewHolder holder) {
        State.Location currentLocation = state.getCurrentLocation();
        if (currentLocation != null) {
            // 如果有当前位置信息，显示完整的位置信息
            holder.locationAddress.setText(currentLocation.getAddress() != null ? 
                currentLocation.getAddress() : "");
            holder.currentLocation.setText(currentLocation.getName());
            holder.locationType.setText(state.getCurrentLocationType());
            holder.btnMarkLocation.setVisibility(
                state.getCurrentLocationType().equals("未标记") ? View.VISIBLE : View.GONE
            );
        } else {
            // 如果没有当前位置信息，显示空白
            holder.locationAddress.setText("");
            holder.currentLocation.setText("");
            holder.locationType.setText("未标记");
            holder.btnMarkLocation.setVisibility(View.VISIBLE);
        }
    }

    private void setupListeners(ViewHolder holder) {
        // 心情和健康状况监听器
        holder.moodSelector.setOnMoodSelectedListener(mood -> {
            state.setMood(mood);
            saveState();
        });
        
        holder.healthSelector.setOnHealthSelectedListener(health -> {
            state.setHealth(health);
            saveState();
        });

        // 更新位置按钮
        holder.btnUpdateLocation.setOnClickListener(v -> {
            updateCurrentLocation();
        });

        // 标记地点按钮（ImageButton）
        holder.btnMarkLocation.setOnClickListener(v -> {
            if (state.getCurrentLocation() != null) {
                LocationTypeDialog dialog = LocationTypeDialog.newInstance(state);
                dialog.setOnTypeSelectedListener(type -> {
                    String currentCityName = state.getCurrentCity().getName();
                    
                    // 获取或创建城市的标记列表
                    Map<String, List<State.LocationMark>> cityMarks = state.getCityMarks();
                    if (!cityMarks.containsKey(currentCityName)) {
                        cityMarks.put(currentCityName, new ArrayList<>());
                    }
                    
                    // 创建新的标记
                    State.LocationMark mark = new State.LocationMark(
                        state.getCurrentLocation(),
                        type,
                        state.getCurrentCityType()
                    );
                    
                    // 添加到标记列表
                    cityMarks.get(currentCityName).add(mark);
                    
                    // 更新当前位置类型
                    state.setCurrentLocationType(type);
                    
                    // 保存状态并更新界面
                    saveState();
                    notifyDataSetChanged();
                    Toast.makeText(context, "已添加标记: " + type, Toast.LENGTH_SHORT).show();
                });
                dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "location_type");
            } else {
                Toast.makeText(context, "请先获取或选择一个位置", Toast.LENGTH_SHORT).show();
            }
        });

        // 城市管理按钮
        holder.btnManageCities.setOnClickListener(v -> {
            showCityManageDialog();
        });

        // 标记地点类型按钮
        holder.btnManageLocationTypes.setOnClickListener(v -> {
            LocationTypeManageDialog dialog = LocationTypeManageDialog.newInstance(state);
            dialog.setOnLocationUpdateListener(() -> {
                saveState();
                notifyDataSetChanged();
            });
            dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "location_type_manage");
        });

        // 查看城市与标记按钮
        holder.btnManageLocations.setOnClickListener(v -> {
            LocationManageDialog dialog = LocationManageDialog.newInstance(state);
            dialog.setOnLocationUpdateListener(() -> {
                saveState();
                notifyDataSetChanged();
            });
            dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "location_manage");
        });
    }

    private void updateCurrentLocation() {
        try {
            AMapLocationClient.updatePrivacyShow(context, true, true);
            AMapLocationClient.updatePrivacyAgree(context, true);
            AMapLocationClient locationClient = new AMapLocationClient(context);
            
            AMapLocationClientOption option = new AMapLocationClientOption();
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setOnceLocation(true);
            option.setNeedAddress(true);
            option.setMockEnable(true);
            locationClient.setLocationOption(option);

            locationClient.setLocationListener(aMapLocation -> {
                if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                    // 获取位置名称（优先使用POI名称）
                    String locationName;
                    if (aMapLocation.getPoiName() != null && !aMapLocation.getPoiName().isEmpty()) {
                        locationName = aMapLocation.getPoiName();
                    } else if (aMapLocation.getAoiName() != null && !aMapLocation.getAoiName().isEmpty()) {
                        locationName = aMapLocation.getAoiName();
                    } else {
                        locationName = aMapLocation.getStreet() != null ? aMapLocation.getStreet() : "未知位置";
                    }

                    // 构建完整地址
                    StringBuilder addressBuilder = new StringBuilder();
                    if (aMapLocation.getProvince() != null) {
                        addressBuilder.append(aMapLocation.getProvince());
                    }
                    if (aMapLocation.getCity() != null) {
                        addressBuilder.append(aMapLocation.getCity());
                    }
                    if (aMapLocation.getDistrict() != null) {
                        addressBuilder.append(aMapLocation.getDistrict());
                    }
                    if (aMapLocation.getStreet() != null) {
                        addressBuilder.append(aMapLocation.getStreet());
                    }

                    // 创建位置对象
                    State.Location location = new State.Location(
                        locationName,
                        aMapLocation.getLatitude(),
                        aMapLocation.getLongitude()
                    );
                    location.setAddress(addressBuilder.toString());

                    // 更新状态
                    state.setCurrentLocation(location);
                    saveState();
                    notifyDataSetChanged();
                } else {
                    String errorMessage = aMapLocation != null ? 
                        "错误码: " + aMapLocation.getErrorCode() + ", 错误信息: " + aMapLocation.getErrorInfo() :
                        "获取位置失败";
                    Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show();
                }
                locationClient.onDestroy();
            });

            locationClient.startLocation();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(context, "获取位置失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void markCurrentLocation() {
        LocationTypeDialog dialog = LocationTypeDialog.newInstance(state);
        dialog.setOnTypeSelectedListener(type -> {
            State.Location currentLocation = state.getCurrentLocation();
            String currentCityName = state.getCurrentCity().getName();
            
            // 获取或创建城市的标记列表
            Map<String, List<State.LocationMark>> cityMarks = state.getCityMarks();
            if (!cityMarks.containsKey(currentCityName)) {
                cityMarks.put(currentCityName, new ArrayList<>());
            }
            
            // 创建新的标记
            State.LocationMark mark = new State.LocationMark(
                currentLocation,
                type,
                state.getCurrentCityType()
            );
            
            // 添加到标记列表
            cityMarks.get(currentCityName).add(mark);
            
            // 更新当前位置类型
            state.setCurrentLocationType(type);
            
            // 保存状态并更新界面
            saveState();
            notifyDataSetChanged();
            Toast.makeText(context, "已添加标记: " + type, Toast.LENGTH_SHORT).show();
        });
        dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "location_type");
    }

    private void showLocationMarkDialog() {
        LocationMarkDialog dialog = LocationMarkDialog.newInstance(state);
        dialog.setOnLocationMarkListener(type -> {
            state.setCurrentLocationType(type);
            saveState();
            notifyDataSetChanged();
        });
        dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "location_mark");
    }

    private void showCityManageDialog() {
        CityManageDialog dialog = CityManageDialog.newInstance(state);
        dialog.setOnCityUpdateListener(() -> {
            saveState();
            notifyDataSetChanged();
        });
        dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "city_manage");
    }

    private void showLocationManageDialog() {
        LocationManageDialog dialog = LocationManageDialog.newInstance(state);
        dialog.setOnLocationUpdateListener(() -> {
            saveState();
            notifyDataSetChanged();
        });
        dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "location_manage");
    }

    private void showLocationTypeManageDialog() {
        LocationTypeManageDialog dialog = LocationTypeManageDialog.newInstance(state);
        dialog.setOnLocationUpdateListener(() -> {
            saveState();
            notifyDataSetChanged();
        });
        dialog.show(((FragmentActivity) context).getSupportFragmentManager(), "location_type_manage");
    }

    private void saveState() {
        File dataDir = new File(Environment.getExternalStorageDirectory(), "BingoBox/data");
        File stateFile = new File(dataDir, "state.json");
        
        try (FileWriter writer = new FileWriter(stateFile)) {
            gson.toJson(state, writer);
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "保存状态失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        final TextView currentCity;
        final TextView cityType;
        final TextView locationAddress;
        final TextView currentLocation;
        final TextView locationType;
        final ImageButton btnMarkLocation;
        final TextView btnUpdateLocation;
        final MoodSelector moodSelector;
        final HealthSelector healthSelector;
        final Button btnManageCities;
        final Button btnManageLocationTypes;
        final Button btnManageLocations;

        ViewHolder(View view) {
            super(view);
            currentCity = view.findViewById(R.id.current_city);
            cityType = view.findViewById(R.id.city_type);
            locationAddress = view.findViewById(R.id.location_address);
            currentLocation = view.findViewById(R.id.current_location);
            locationType = view.findViewById(R.id.location_type);
            btnMarkLocation = view.findViewById(R.id.btn_mark_location);
            btnUpdateLocation = view.findViewById(R.id.btn_update_location);
            moodSelector = view.findViewById(R.id.mood_selector);
            healthSelector = view.findViewById(R.id.health_selector);
            btnManageCities = view.findViewById(R.id.btn_manage_cities);
            btnManageLocationTypes = view.findViewById(R.id.btn_manage_location_types);
            btnManageLocations = view.findViewById(R.id.btn_manage_locations);
        }
    }
} 